package com.example.demo.controller;

import com.example.demo.utils.QRCodeUtil;
import com.example.demo.utils.ZipHelper;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/zipDownLoadServlet")
public class ZipDownLoadController {

    private Logger logger = LoggerFactory.getLogger(ZipDownLoadController.class);

    @RequestMapping("/downZip")
    public void downZip(HttpServletResponse response, String realPath) {

        //1 生成二维码
        String projectName = "压缩文件";
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }

        List<String> list = Arrays.asList("code11.jpg", "code22.jpg", "code33.jpg");//已经存好的图片
        try {
            for (String x : list) {
                String logo = realPath + "/" + x;
                String outPutFile = realPath + "/qrcode/" + x;
                String url = "https://www.baidu.com/?name=" + x;
                QRCodeUtil.generateQRImage(url, outPutFile, logo);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        //2 生成zip文件
        String filename = projectName + ".zip";
        String zipFileName = realPath + filename;
        try {
            ZipHelper.zipCompress(realPath, zipFileName);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        try {
            //3 下载
            //设置文件MIME类型
            response.setContentType("application/zip");// 定义输出类型
            response.setCharacterEncoding("UTF-8");
            //设置Content-Disposition
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }

        try (
                InputStream in = new FileInputStream(zipFileName);
                OutputStream out = response.getOutputStream();
        ) {
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);

            //4 删除多余文件
            ZipHelper.deleteDir(new File(realPath));
            ZipHelper.deleteDir(new File(zipFileName));

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}
